package com.hmall.common.interceptor;

import cn.hutool.core.util.StrUtil;
import com.hmall.common.utils.UserContext;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 微服务拦截器
 *
 * @Author mr.wu
 * @Date 2025-8-23 14:39
 */
public class UserInfoInterceptor implements HandlerInterceptor {

    /**
     * 拦截请求处理逻辑
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String userIdStr = request.getHeader("user-info");
        if(StrUtil.isNotBlank(userIdStr)) {
            Long userId = Long.valueOf(userIdStr);
            UserContext.setUser(userId);
        }
        return true;
    }

    /**
     * 请求处理完毕，结束响应前
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserContext.removeUser();//删除当前线程绑定的数据，避免出现OOM问题
    }
}
